import React, { useState, useEffect } from 'react';
import './ColumnFilterModal.css';

const ColumnFilterModal = ({
  isOpen = false,
  onClose = () => {},
  onConfirm = () => {},
  availableColumns = [],
  selectedColumns = [],
  title = "选择筛选列"
}) => {
  const [localSelectedColumns, setLocalSelectedColumns] = useState(selectedColumns);

  // 当selectedColumns prop变化时，更新本地状态
  useEffect(() => {
    setLocalSelectedColumns(selectedColumns);
  }, [selectedColumns]);

  // 当弹窗打开时，重置为传入的选中状态
  useEffect(() => {
    if (isOpen) {
      setLocalSelectedColumns(selectedColumns);
    }
  }, [isOpen, selectedColumns]);

  const handleCheckboxChange = (columnKey) => {
    setLocalSelectedColumns(prev => {
      if (prev.includes(columnKey)) {
        return prev.filter(key => key !== columnKey);
      } else {
        return [...prev, columnKey];
      }
    });
  };

  const handleConfirm = () => {
    onConfirm(localSelectedColumns);
    onClose();
  };

  const handleCancel = () => {
    setLocalSelectedColumns(selectedColumns); // 重置为原始状态
    onClose();
  };

  const handleOverlayClick = (e) => {
    if (e.target === e.currentTarget) {
      handleCancel();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="column-filter-modal-overlay" onClick={handleOverlayClick}>
      <div className="column-filter-modal">
        <div className="column-filter-modal__header">
          <h3 className="column-filter-modal__title">{title}</h3>
        </div>
        
        <div className="column-filter-modal__body">
          <div className="column-filter-modal__grid">
            {availableColumns.map((column) => (
              <label 
                key={column.key} 
                className="column-filter-modal__checkbox-item"
              >
                <input
                  type="checkbox"
                  checked={localSelectedColumns.includes(column.key)}
                  onChange={() => handleCheckboxChange(column.key)}
                  className="column-filter-modal__checkbox"
                />
                <span className="column-filter-modal__checkbox-label">
                  {column.title}
                </span>
              </label>
            ))}
          </div>
        </div>
        
        <div className="column-filter-modal__footer">
          <button 
            className="column-filter-modal__btn column-filter-modal__btn--confirm"
            onClick={handleConfirm}
          >
            确定
          </button>
          <button 
            className="column-filter-modal__btn column-filter-modal__btn--cancel"
            onClick={handleCancel}
          >
            取消
          </button>
        </div>
      </div>
    </div>
  );
};

export default ColumnFilterModal;
